#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5, inf = 1e9+100;
int T,n,x,y,d;
int main() {
    cin >> T;
    while (T--)
    {
        cin >> n >> x >> y >> d;
        if((y-x) % d == 0) {
            cout << abs(y-x) / d << endl;
        } else {
            int ans = inf;
            if(y % d == 1) {
                int k1 = ceil( (x-1)*1.0 / d );
                int k2 = (y-1) / d;
                ans = k1 + k2;
            }  
            if(n%d == y %d) {
                int k1 = ceil( (n-x)*1.0 / d );
                int k2 = (n-y) / d;
                ans = min(ans, k1+k2);
            }
            if(ans == inf) cout << -1 << endl;
            else cout << ans << endl;
        }
    }
    return 0;
}